import 'dart:async';

import 'package:flutter/material.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/core/models/store_index.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 轮播
class HomeBanner extends StatefulWidget {
  final List<Link> banner;

  const HomeBanner({
    Key key,
    @required this.banner,
  }) : super(key: key);

  @override
  _HomeBannerState createState() => _HomeBannerState();
}

class _HomeBannerState extends State<HomeBanner> {
  PageController _pageController;
  Timer _timer;
  int _index = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: widget.banner.length * 100);
    _timer = Timer.periodic(Duration(seconds: 3), _callback);
  }

  @override
  void dispose() {
    _timer.cancel();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: 160.w,
      child: Stack(
        children: [
          PageView.builder(
            controller: _pageController,
            itemBuilder: _buildPage,
            onPageChanged: _onPageChanged,
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: List.generate(widget.banner.length, _buildDot),
            ),
          )
        ],
      ),
    );
  }

  void _callback(Timer timer) {
    _pageController.nextPage(
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInToLinear,
    );
  }

  void _onPageChanged(int index) {
    setState(() {
      _index = index;
    });
  }

  Widget _buildPage(BuildContext context, int index) {
    final data = widget.banner[index % widget.banner.length];
    return ImageNetwork(url: "${data.image}");
  }

  Widget _buildDot(int index) {
    final selected = index == _index % widget.banner.length;
    return Container(
      width: 6.w,
      height: 6.w,
      margin: EdgeInsets.symmetric(
        vertical: 6.w,
        horizontal: 3.w,
      ),
      decoration: BoxDecoration(
        color: selected ? Colors.black : Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(3.w)),
      ),
    );
  }
}
